<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
            <el-form-item label="编码" prop="typeBm">
                <el-input v-model="queryParams.typeBm" placeholder="请输入编码" clearable size="small"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入名称" clearable size="small"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
                    <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="客户端" prop="wxClientId" v-if="handleCheckRole('admin')">
                <el-select v-model="queryParams.wxClientId" placeholder="请选择客户端" clearable size="small">
                    <el-option v-for="item in clientList" :key="item.id" :label="item.name"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['zx:article:type:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['zx:article:type:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['zx:article:type:remove']">删除</el-button>
            </el-col>
            <!--      <el-col :span="1.5">-->
            <!--        <el-button-->
            <!--          type="warning"-->
            <!--          icon="el-icon-download"-->
            <!--          size="mini"-->
            <!--          @click="handleExport"-->
            <!--          v-hasPermi="['zx:article:type:export']"-->
            <!--        >导出</el-button>-->
            <!--      </el-col>-->
        </el-row>

        <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" align="center" prop="id" />
            <el-table-column label="编码" align="center" prop="typeBm" />
            <el-table-column label="名称" align="center" prop="name" />
            <el-table-column label="类型图片" align="center" prop="logo">
                <template slot-scope="scope">
                    <el-image :src="base_url + scope.row.logo" style="height: 40px;width: 40px" />
                </template>
            </el-table-column>
            <el-table-column label="排序" align="center" prop="sort" />
            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <span :class="'verifyStatus_' + scope.row.status">{{ statusFormat(scope.row) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="客户端" align="center" prop="clientName" v-if="handleCheckRole('admin')" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['zx:article:type:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['zx:article:type:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改资讯-文章类型对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="编码" prop="typeBm">
                    <el-input v-model="form.typeBm" placeholder="请输入编码" />
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入名称" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="form.status" placeholder="请选择状态">
                        <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                            :value="dict.dictValue"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="form.sort" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入排序" />
                </el-form-item>
                <el-form-item label="类型图片" prop="logo">
                    <el-upload class="avatar-uploader" :action="url" :show-file-list="false" :on-success="uploadSuccess"
                        :limit="1" :file-list="fileList" :headers="headers" :before-upload="checkUpload"
                        :disabled="flag">
                        <img v-if="files.path" :src="base_url + files.path" class="avatar" width="100px" height="100px">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="客户端" v-hasRole="['admin']">
                    <wx-client :client-id="form.wxClientId" @wx-client="wxClient"></wx-client>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listType, getType, delType, addType, updateType, exportType } from "@/api/zx/type";
import { getToken } from "@/utils/auth";
import { listClient } from "@/api/wx/client";
import { checkPermi, checkRole } from "@/utils/permission.js";
import WxClient from "@/views/components/wx-client/wx-client";

export default {
    name: "Type",
    components: { WxClient },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 资讯-文章类型表格数据
            typeList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 状态字典
            statusOptions: [],
            // 删除标志字典
            delFlagOptions: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                typeBm: undefined,
                name: undefined,
                status: undefined,
                wxClientId: undefined,
                sort: undefined,
                logo: undefined
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                name: [
                    { required: true, message: "名称不能为空", trigger: "blur" }
                ],
                typeBm: [
                    { required: true, message: "编码不能为空", trigger: "blur" }
                ],
                status: [{
                    required: true,
                    message: '请选择状态',
                    trigger: 'blur'
                }],
            },
            base_url: process.env.VUE_APP_BASE_API,
            //文件列
            fileList: [],
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            //上传地址
            url: process.env.VUE_APP_BASE_API + "/common/upload",
            //是否禁用上传
            flag: false,
            //图片路径
            files: { path: '' },
            clientList: []
        };
    },
    created() {
        this.getList();
        this.getDicts("article_type_status").then(response => {
            this.statusOptions = response.data;
        });
        this.getDicts("article_type_del_flag").then(response => {
            this.delFlagOptions = response.data;
        });
        listClient().then(response => {
            this.clientList = response.rows;
        });
    },
    methods: {
        /** 查询资讯-文章类型列表 */
        getList() {
            this.loading = true;
            listType(this.queryParams).then(response => {
                this.typeList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 状态字典翻译
        statusFormat(row, column) {
            return this.selectDictLabel(this.statusOptions, row.status);
        },
        // 删除标志字典翻译
        delFlagFormat(row, column) {
            return this.selectDictLabel(this.delFlagOptions, row.delFlag);
        },
        handleCheckRole(v) {
            return checkRole([v]);
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                typeBm: undefined,
                name: undefined,
                status: "0",
                delFlag: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                wxClientId: undefined,
                sort: 0,
                logo: undefined
            };
            this.resetForm("form");
            this.fileList = [];
            this.flag = false
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getType(id).then(response => {
                this.files.path = response.data.logo;
                console.log("回显数据：");
                console.log(response.data);
                this.form = response.data;
                this.open = true;
                this.title = "修改";
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != undefined) {
                        updateType(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("修改成功");
                                this.open = false;
                                this.getList();
                            }
                        });
                    } else {
                        addType(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getList();
                            }
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm('是否确认删除资讯-文章类型编号为"' + ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delType(ids);
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(function () { });
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm('是否确认导出所有资讯-文章类型数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return exportType(queryParams);
            }).then(response => {
                this.download(response.msg);
            }).catch(function () { });
        }
        ,
        /**关闭dialog的按钮触发*/
        closeDialog() {
            if (this.files.path != undefined && this.files.path != '') {
                console.log("关闭dialog触发删除")
                delFile(this.files).then(response => {
                    this.files.path = undefined;
                    console.log(response)
                })
            }
        },
        /** 上传之前的校验 */
        checkUpload(file) {
            console.log("文件类型", file)
            const imgType = file.type
            //图片不大于2M
            const isLtSize = file.size / 1024 / 1024 < 2
            if (['image/png', 'image/jpeg', 'image/jpg', 'image/gif'].indexOf(imgType) === -1) {
                this.$message.error('上传图片只能是 JPG、PNG、GIF格式!')
                return false;
            }
            if (!isLtSize) {
                this.$message.error(`上传图片大小不能超过2MB!`)
                return false;
            }
        },
        /** 上传成功后的回调 */
        uploadSuccess(response, file, fileList) {
            console.log("1111");
            this.form.logo = response.fileName
            this.files.path = response.fileName
            this.flag = true
        },
        wxClient(e) {
            this.form.wxClientId = e;
        }
    }
};
</script>

<style scoped>
.avatar-uploader i {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader i:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
}

.form {
    height: 600px;
}

.verifyStatus_0 {
    color: red !important;
}

.verifyStatus_1 {
    color: green;
}
</style>